
var pnum = "";
var initData = function(num){
	    var param = {
			page_num:num,
			page_size:"10"
	    }
		$.ajax({
	        url: base + "/dataCenter/businessdata/findDesignContent",
	        data: param,
	        success: function (data, textStatus, jqXHR) {
	        	var pageCount = data.pager.pageCount;
	        	var dataObj ={
	        			"list":data.list,
	         			"dataTool":{
	         				"title":{
	          			      	"project_design_content_code": "设计内容代码"
	          			      	,"project_design_content_name": "设计内容名称"
	          			      	,"major_name":"所属专业"
	          			      	,"is_gis":"是否添加gis标注"
	          			      	,"create_time":"创建时间"
	          			      	,"update_time":"修改时间"
	          			      	,"operation":"操作"
	            			},
                            "stateData":[{"stateField":"is_gis","stateArray":[{1:"是"},{0:"否"}]}],
                            "titleCheckbox":false,
							"btn":[{"event":"updateObj","name":"编辑"},
							       {"event":"delObj","name":"删除"},
							       {"event":"matchingMajor","name":"依赖专业"},
							       {"event":"addProjectProperty","name":"项目属性"}]
						}
		  		};
	        	showPageTable('view', dataObj,num,pageCount,"initData");
	        },
	        error: function () {
	        }
	    });
   }

   var searchObj = function (num) {
       if (num==undefined|| num==""||num.type=="click" ) {
           num=1;
       }
	   var name=$("#searchName").val();
       var param = {
           page_num:num,
           page_size:"10",
           content_name:name
       }
       $.ajax({
           url: base + "/dataCenter/businessdata/findDesignContent",
           data: param,
           success: function (data, textStatus, jqXHR) {
               var pageCount = data.pager.pageCount;
               var dataObj ={
                   "list":data.list,
                   "dataTool":{
                       "title":{
                           "project_design_content_code": "设计内容代码"
                           ,"project_design_content_name": "设计内容名称"
                           ,"major_name":"所属专业"
                           ,"is_gis":"是否添加gis标注"
                           ,"create_time":"创建时间"
                           ,"update_time":"修改时间"
                           ,"operation":"操作"
                       },
                       "titleCheckbox":false,
                       "btn":[{"event":"updateObj","name":"编辑"},
                           {"event":"delObj","name":"删除"},
                           {"event":"matchingMajor","name":"匹配依赖专业"},
                           {"event":"addProjectProperty","name":"添加项目属性"}]
                   }
               };
               showPageTable('view', dataObj,num,pageCount,"searchObj");
           },
           error: function () {
           }
       });
	}
   //添加项目属性
   var addProjectProperty = function(obj){
	   var code = $.trim(obj.project_design_content_code)+"_project_property";
	   openStructurLay(code);
   }
   
   //取得非结构表单信息
   var initNoFormField = function(code){
	   var contentDiv;
	   $.ajax({
		   url:base+"/dataCenter/findNoFromFieldHtml/"+code,
		   data:{},
		   async: false,
		   success:function(data,status){
			   contentDiv = data;
		   }
	   });
	   return contentDiv;
   }
   
   
   //打开结构化数据维护弹窗
   var openStructurLay = function(code){
		layer.open({
		  	title:'编辑项目所属属性'
			,content:initNoFormField(code)
	    	,area: ['1150px', '600px']
		    ,scrollbar: false
		  	,btn: ['保存', '取消']
			,yes: function(index,layero){ //确认
				commit_field_data(code);
			}
	    });
   }
   
   //校验数据
   var verify_data = function(){
	   var juage = true;
	   var data_obj = $("#from_field_table").children("tr");
	   $.each(data_obj,function(index,value){
		   if(index>1){
			   $.each($(this).children("td"),function(children_index,value){
				   if(children_index > 1){
					   var obj_name = $(this).children().attr("name");
					   var obj_val = $(this).children().val();
					   if("field_type"==obj_name && ("varchar"==obj_val || "int"==obj_val)){
						   var field_length_obj = $(this).parent().find("td input[name='field_length']");
						   if(field_length_obj.val() == "" || field_length_obj.val() == undefined){
							   field_length_obj.focus();
							   layer.tips('字段长度不能为空', field_length_obj);
							   juage = false;
							   return false;
						   }
					   }
					   if("field_name"==obj_name && (""==obj_val || undefined==obj_val)){
						   var field_name_obj = $(this).parent().find("td input[name='field_name']");
						   field_name_obj.focus();
						   layer.tips('字段名不能为空', field_name_obj);
						   juage = false;
						   return false;
					   }
					   if("widget_length"==obj_name && (""==obj_val || undefined==obj_val)){
						   var field_name_obj = $(this).parent().find("td input[name='widget_length']");
						   field_name_obj.focus();
						   layer.tips('控件长度不能为空', field_name_obj);
						   juage = false;
						   return false;
					   }
					   if("field_comment"==obj_name && (""==obj_val || undefined==obj_val)){
						   var field_name_obj = $(this).parent().find("td input[name='field_comment']");
						   field_name_obj.focus();
						   layer.tips('字段备注不能为空', field_name_obj);
						   juage = false;
						   return false;
					   }
				   }
			   });
			   if(!juage){
				   return false;
			   }
		   }
	   });
	   return juage;
   }
   
   //封装结构化表单数据
   var commit_field_data = function(code){
	   if(false==verify_data()){
		   return false;
	   }
	   var json_array = [];
	   var data_obj = $("#from_field_table").children("tr");
	   $.each(data_obj,function(index,value){
		   if(index > 1){
			   var json_str = {};
			   $.each($(this).children("td"),function(children_index,value){
				   if(children_index > 1){
					   var input_obj = $(this).children();
					   var input_name = $(this).children().attr("name");
					   if(input_name=="field_name"){
						   json_str['field_name']=$.trim(input_obj.val());
					   }else if(input_name=="field_comment"){
						   json_str['field_comment']=$.trim(input_obj.val());
					   }else if(input_name=="field_length"){
						   json_str['field_length']=$.trim(input_obj.val());
					   }else if(input_name=="field_default"){
						   json_str['field_default']=$.trim(input_obj.val());
					   }else if(input_name=="field_type"){
						   json_str['field_type']=$.trim(input_obj.val());
					   }else if(input_name=="is_null"){
						   if(input_obj.is(':checked')){
							   json_str['is_null']='true';
						   }else{
							   json_str['is_null']='false';
						   }
					   }else if(input_name=="widget_type"){
						   json_str['widget_type']=$.trim(input_obj.val());
					   }else if(input_name=="widget_length"){
						   json_str['widget_length']=$.trim(input_obj.val());
					   }else if(input_name=="is_show"){
						   if(input_obj.is(':checked')){
							   json_str['is_show']='true';
						   }else{
							   json_str['is_show']='false';
						   }
					   }
				   }
			   });
			   json_array.push(json_str);
		   }
	   });
	   var field_list = JSON.stringify(json_array);
	   var table_name = code;
	   var param = {"table_name":table_name,"data_list":field_list};
	   commit_data(param);
   } 
   
   var commit_data = function(param){
	   $.post(base+"/dataCenter/businessdata/updateTableField",param,
		       function(data,status){
			     if(data.statusCode == 0){
				  	layer.msg(data.message, {
						icon : 1
				  	});
			     }else{
					layer.msg(data.message, {
						icon : 5
					});
			    }
		  });
   }

   var delObj = function(obj){
	   layer.confirm('确认删除?',{btn : [ '确定', '取消' ]},function(index){
		   layer.close(index);
		   var param = {id:obj.id}
		   $.ajax({
			   url:base+"/dataCenter/businessdata/delDesignContentById",
			   data:param,
			   success:function(data,status){
				    if(data.statusCode == 0){
						layer.msg(data.message, {
							icon : 1
						});
				    }else{
						layer.msg(data.message, {
							icon : 5
						});
				    }
				    initData(pnum);
			   }
		   });
	   });
   }
   var addObj = function(){
	   var contentDIV = function(){
		   var content;
		   var data = {
				   "title":{
					   "content_code":"设计内容代码",
					   "content_name":"设计内容名称",
					   "major_id":"专业名称"
				   },"text":{
					   "content_code":"",
					   "content_name":"",
					   "major_id":""
				   },"input":{
					   "content_code":"text",
					   "content_name":"text",
					   "major_id":"select"
				   },"input_init":{
				   }
		   };
		   var getDiv = dc_update.innerHTML;
		   laytpl(getDiv).render(data,function(html){
			   content = html;
		   });
		   return content;
	   }
	   layopen(contentDIV());
	   initDesignMajor();
   }
   
   var initDesignMajor = function(){
	   $.post(base+"/dataCenter/businessdata/findDesignMajorData",{},
   		  	function(data,status){
     		    	if(data!=''){
   	      		  	 var optionstring = "";
   	                 $.each(data.list, function(i,item){
   	                    optionstring += "<option value=\"" + item.id + "\" >" + item.project_design_major_name + "</option>";
   	                });
   	                $("#select").html('<option value=""></option>' + optionstring);
   	      		}else{
   	      		  	$("#select").html('<option value=""></option>');
   	      		}
     		    form.render(); 
  });
  }




   var updateObj = function(obj){
		var contentDiv = function(){
			var content;
			var data={
					"title":{
						    "id":"唯一标识",
						    "major_id":"专业id",
					      	"content_code": "设计内容代码",
					      	"content_name":"设计内容名称",
					      	"major_name":"所属专业"
					},"text":{
						    "id":obj.id==null?"":obj.id
						    ,"major_id":obj.project_design_major_id==null?"":obj.project_design_major_id
						    ,"major_name":obj.major_name==null?"":obj.major_name
							,"content_code":obj.project_design_content_code==null?"":obj.project_design_content_code
							,"content_name":obj.project_design_content_name==null?"":obj.project_design_content_name
					},"input":{
						    "id":"hidden"
						    ,"major_id":"hidden"
						    ,"major_name":"text_readonly"
							,"content_code":"text"
							,"content_name":"text"
					},"input_init":{
					}
			};
			var getDiv =  dc_update.innerHTML;
			laytpl(getDiv).render(data, function(html){
				content = html;
			}); 
			return content;
		}
		layopen(contentDiv());
   }
   
   var layopen = function(content){
		layer.open({
		  	title:'更新设计内容'
			,content: content
	    	,area: ['800px', '500px']
		    ,scrollbar: false
		  	,btn: ['确认', '取消']
			,yes: function(index,layero){ //确认
				var data = $(layero).find("form").serializeJSON();
				if(data.content_code == ''){
					var obj = $("input[name='content_code']");
					obj.focus();
					layer.tips('请填写此字段!', obj);
					return false;
				}
				if(data.content_name == ''){
					var obj = $("input[name='content_name']");
					obj.focus();
					layer.tips('请填写此字段!', obj);
					return false;
				}
				if(data.major_id == ''){
					alert("请选择专业!")
					return false;
				}
				$.post(base+"/dataCenter/businessdata/updateDesignContent",{
					id:data.id==null?"":data.id,
					project_design_major_id:data.major_id,
					project_design_content_code:$.trim(data.content_code),
					project_design_content_name:$.trim(data.content_name)
				},
		  		function (data,status){
					if(data!=""&&data!=null){
						if(data.statusCode == 0){
							layer.msg('更新成功', {icon: 1,time:2000});
						}else{
							layer.msg(data.message, {icon: 2,time:2000});
						}
					}else{
						layer.msg('更新失败!', {icon: 2,time:2000});
					}
					initData(pnum);
		  		 })
			}
	});
   }
   
   var initContentMajor = function(obj){
	   $.post(base+"/dataCenter/businessdata/findMatchingMajorList",{content_id:obj.id},
	   		  	function(data,status){
	     		    	if(data!=''){
	   	      		  	 var checkboxString = "";
	   	                 $.each(data, function(i,item){
	   	                	//if(obj.project_design_major_id != item.major_id){ //只能匹配非本专业的其它相关专业
	   	                		if(item.content_id != null && item.content_id != ""){
	   	                			checkboxString += " <input name = "+item.major_id+" title = "+item.major_name+" type='checkbox' checked='' >";
	   	                		}else{
	   	                			checkboxString += " <input name = "+item.major_id+" title = "+item.major_name+" type='checkbox'>";
	   	                		}
	   	                //	}
	   	                });
	   	                $("#checkbox").html(checkboxString);
	   	      		}else{
	   	      		  	$("#checkbox").html();
	   	      		}
	     		    form.render(); 
	   });
	   form.render();
   }
   
   
   //匹配相关专业
   var matchingMajor = function(obj){
		var contentDiv = function(){
			var content;
			var data={
					"title":{
						    "content_id":"设计内容唯一标识",
					      	"content_name":"设计内容名称",
					      	"major_ids":"选择依赖专业"
					},"text":{
						    "content_id":obj.id==null?"":obj.id
							,"content_name":obj.project_design_content_name==null?"":obj.project_design_content_name
							,"major_ids":""
					},"input":{
						    "content_id":"hidden"
							,"content_name":"text_readonly"
							,"major_ids":"checkbox"
					},"input_init":{
					}
			};
			var getDiv =  dc_update.innerHTML;
			laytpl(getDiv).render(data, function(html){
				content = html;
			}); 
			return content;
   }
			layer.open({
			  	title:'匹配专业'
				,content: contentDiv()
		    	,area: ['800px', '500px']
			    ,scrollbar: false
			  	,btn: ['确认', '取消']
				,yes: function(index,layero){ //确认
					var data = $(layero).find("form").serializeJSON();
					if(JSON.stringify(data).split(",").length <= 1){
						alert("请选择专业!");
						return false;
					};
					var content_id = data.content_id;
					var major_arr = new Array();
					$.each($('input[type=checkbox]:checked'),function(index,value){
						major_arr.push($(this).attr("name"));
					});
					var major_str = major_arr.join(",");
					$.post(base+"/dataCenter/businessdata/addDesignContentCorrelationMajor",{
						content_id:content_id,
						major_ids:major_str
					},
			  		function (data,status){
						if(data!=""&&data!=null){
							if(data.statusCode == 0){
								layer.msg('更新成功', {icon: 1,time:2000});
							}else{
								layer.msg(data.message, {icon: 2,time:2000});
							}
						}else{
							layer.msg('更新失败!', {icon: 2,time:2000});
						}
						initData(pnum);
			  		 })
					
				}
		    });
			initContentMajor(obj);
   }
   $(document).ready(function(){
	   initData(1);
	   $("#addData").click(addObj);
       $("#searchInfo").click(searchObj);
   });